package com.qianniu.napi.common.shiro;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.MerchantApp;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.AesUtil;
import com.qianniu.napi.common.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//public class TokenFilter extends AccessControlFilter {
@Component
@WebFilter(urlPatterns = {"/api/*"}, filterName = "tokenFilter")
public class TokenFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    public TokenFilter() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;

        log.info("========preHandle come");
        String requrl = req.getRequestURI();
        log.info("-------------------------------------------------url=" + requrl);
        log.info("-------------------------------------------------QueryString=" + req.getQueryString());
        log.info("-------------------------------------------------req.getMethod()=" + req.getMethod());
        log.info("========guid=" + request.getParameter("g"));
        if(requrl.indexOf("/api/")!=0){
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = (HttpSession) req.getSession();
        MerchantApp merchant = null;
        boolean noauth = false;
        if (request.getParameter("t") != null) {
            String token = java.net.URLDecoder.decode(request.getParameter("t"), "UTF-8");
            log.debug(">>>token=" + token);
            merchant = getMerchantByToken(token);
            if (merchant == null) noauth = true;
        } else {
            noauth = true;
        }


        if (noauth) {
            Jinfo info = new Jinfo();
            info.setCode(1);
            info.setMsg("no auth info");
            response.setContentType("application/json; charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(JSON.toJSONString(info).getBytes("UTF-8"));
            return;
        }

        if (merchant.getUid() != null) session.setAttribute("uid", merchant.getUid());
        session.setAttribute("mid", merchant.getMid());
        session.setAttribute("appid", merchant.getAppid());
        session.setAttribute("mpid", merchant.getId());
        session.setAttribute("appType", merchant.getAppType());
        session.setAttribute("sid", merchant.getSid());
        session.setAttribute("guid", request.getParameter("g"));
        session.setAttribute("subsid", merchant.getSubsid());
        session.setAttribute("mainmpid", merchant.getMainmpid());

        log.info("----------------------------------------------session.setAttribute over ");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private MerchantApp getMerchantByToken(String token) {
        log.info(">>>>>>>>>>>>>>>getMerchantByToken start and token=" + token);

        if (Strings.isNullOrEmpty(token)) return null;
        MerchantApp mapp = new MerchantApp();

        IRedisService redis = (IRedisService) SpringUtil.getBean("redisServiceImpl");

        String key = redis.get(token);
        log.info("======>>>>>>>key=" + key);

        String data = Strings.isNullOrEmpty(key) ? AesUtil.decrypt(token, Constants.ENCODE_KEY) : key;
        log.info("-------------------------------------------------------------getMerchantByToken key=" + data);
        if (data == null) return null;
        log.info(">>>data=" + data);
        String[] mainvals = data.split("##");
        log.debug("------------------------------------------------------------mainvals.size=" + mainvals.length);
        String[] vals = mainvals[0].split("__");
        try {
            if (mainvals.length >= 2) mapp.setMainmpid(Long.valueOf(mainvals[1]));
        } catch (Exception e) {
            log.error("mapp.setMainmpid error for mainvals[1]=" + mainvals[1]);
        }

        if (vals.length <= 3) return null;

        try {
//        mid+mpid+[uid]+random+appid+apptype+sid##mainmpid
            mapp.setMid(Long.valueOf(vals[0]));
            mapp.setId(Long.valueOf(vals[1]));

            if (!Strings.isNullOrEmpty(vals[2]) && !vals[2].equals("null")) {
                mapp.setUid(Long.valueOf(vals[2]));
            }

            if (vals.length >= 5) {
                mapp.setAppid(vals[4]);
            }
            if (vals.length >= 6) {
                mapp.setAppType(Integer.valueOf(vals[5]));
            }
            if (vals.length >= 7) {
                mapp.setSid(Long.valueOf(vals[6]));
            }
        } catch (Exception e) {
            log.info("parse token error", e);
            return null;
        }
        log.info(">>>merchant=" + JSON.toJSONString(mapp));
        return mapp;
    }
}
